<template>
  <div class="main">
    <div class="header">
      <a href="/">
        <img>
      </a>
      <h1>用户登录</h1>
    </div>
    <el-form ref="loginForm" :rules="formRules" :model="form" label-width="0px">
      <el-form-item prop="email">
        <label for="">邮箱</label>
        <el-input placeholder="请输入Email" prefix-icon="el-icon-user-solid" v-model="form.email" type="email" autofocus>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <label for="">密码</label>
        <el-input placeholder="请输入密码" prefix-icon="el-icon-lock" v-model="form.password" show-password type="password">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="checked" style="margin-right: 50px">记住我</el-checkbox>
        <el-link type="primary">忘记密码?</el-link>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width:100%" @click="loginvalidate()">登录</el-button>
      </el-form-item>
    </el-form>
    <div class="message">
      <p>没有账号? <router-link to='./register'>点击创建</router-link>.</p>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      checked: true,
      form: {
        email: window.localStorage.getItem('account'),
        password: ''
      },
      formRules: {
        email: [
          { required: true, message: '请输入Email', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 14, message: '长度在 6 到 14 个字符且必须包含字母', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    loginvalidate() {
      this.$refs.loginForm.validate(async val => {
        if (!val) { return }
        var ret = await this.$http.post('/login', this.form)
        console.log(ret.data)
        if (ret.data.err_code === 0) {
          this.$message({
            message: '恭喜你,登陆成功!',
            type: 'success'
          })
          window.localStorage.setItem('token', ret.data.token)
          this.$router.push({ path: '/Home' })
        } else {
          this.$message({
            message: '登陆失败,账号不存在或与密码不匹配!',
            type: 'error'
          })
        }
      })
    }
  }

}

</script>
<style scoped>
body {
  background-color: #f9f9f9;
}

.main {
  width: 340px;
  margin: 0 auto;
  margin-top: 50px;
  color: #333;
}

.main .header {
  text-align: center;
}

.main .header h1 {
  font-size: 26px;
}

.main form {
  padding: 20px;
  margin-bottom: 15px;
  border: 1px solid #d8dee2;
  border-radius: 5px;
  background-color: #fff;
}

.main .message {
  padding: 10px;
  padding-bottom: 0;
  border: 1px solid #d8dee2;
  border-radius: 5px;
}

</style>
